/*
收到请求时，把网页响应回去
http://localhost:8081/   将index.html响应到前端
*/
const http = require('http')
const url = require('url')
const fs = require('fs')
const path = require('path')
const https=require('https')
const cheerio = require('cheerio')

var reqUrl="https://maoyan.com/films?showType=3"
var movieList=[]

// req：请求对象的信息；res：向客户端响应的信息（都是流信息）
http.createServer((req, res) => {
    // 解析url为对象
    var urlObj = url.parse(req.url)
    var pathname = urlObj.pathname
    if (pathname == '/') {
        var filePath = path.join(__dirname, '/index.html')
        // 异步方法，数据的接收是在异步回调里面
        fs.readFile(filePath, (err, data) => {
            if (err) {
                console.log(err)
            } else {
                res.writeHead(200, { "Content-type": "text/html;charset=utf8" })
                res.write(data)
                res.end()
            }
        })
    } else if (pathname == '/getlist') {
        https.get(reqUrl,(resObj)=>{
            var htmlStr=''
            resObj.on('data',(chunk)=>{
                // chunk本来是buffer数据，在被字符串+=的过程中，有一个toString的过程
                htmlStr+=chunk
            })
            resObj.on('end',()=>{
                var $=cheerio.load(htmlStr)
                $(".movie-item-title a").each((i,ele)=>{
                    var movieName=$(ele).text()
                    var movieId=$(ele).attr('data-val');
                    movieId=movieId.slice(movieId.indexOf(':')+1,-1)
                    var num1=$(ele).parent().next().children(".integer").text()
                    var num2=$(ele).parent().next().children(".fraction").text()
                    var rate=num1+num2 ? num1+num2 : '暂无评分'
                    var movieObj={movieId:movieId,movieName:movieName,movieRate:rate}
                    movieList.push(movieObj)
                })
                res.writeHead(200,{'Content-Type':"text/plain"})
                res.write(JSON.stringify(movieList))
                res.end()
            })
        })
    }

}).listen(8081)